<script src="__LIB__/jquery/jquery-3.6.1.min.js" charset="utf-8"></script>
<script src="__LIB__/jq-module/jquery.cookie-1.4.1.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="__LIB__/emoji/emoji.css" />
<div id="app" class="chat" style="height:820px;">
    <div class="layui-row">
        <!-- 机器人客服 -->
        <div class="layui-col-xs1 bot">
            <div class="layui-panel bot-panel">
                <ul class="layui-menu bot_list" ref="bot_list_ref">
                    <li v-for="(item, index) in bot_list" :key="item.id" @click="clickFriend(item)"
                        :class="item.id == bot_id ? 'layui-menu-item-checked' : ''">
                        <div class="layui-menu-body-title">
                            <img :src="item.headimgurl" :class="[item.alive?'light_headimgurl':'gray_headimgurl']"
                                style="width:50px;height:50px;border-radius:10%" :title="item.nickname" />
                            <span class="layui-badge-dot" v-if="item.new"></span>
                            <span>{{item.nickname}}</span>

                        </div>
                    </li>
                </ul>
                <div class="layui-menu-body-title">
                    <button type="button" class="layui-btn layui-btn-fluid layui-btn-primary" @click="addBot">
                        <i class="layui-icon layui-icon-add-1"></i>新增
                    </button>
                </div>
            </div>
        </div>
        <!-- 好友列表 -->
        <div class="layui-col-xs3" class="friends">
            <div class="layui-panel friends-panel">
                <div class="layui-form-item" style="padding: 15px;">
                    <div class="layui-row">
                        <div class="layui-col-xs9">
                            <input type="input" name="search" autocomplete="off" class="layui-input"
                                v-model="search_friend" placeholder="输入昵称或备注">
                        </div>
                        <div class="layui-col-xs3">
                            <button type="button" class="layui-btn layui-btn-sm" style="height: 38px;"
                                @click="searchFriend()">搜索</button>
                        </div>
                    </div>
                    <!-- <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-btn-primary" lay-submit="" lay-filter="search"><i class="layui-icon layui-icon-search"></i></button> -->
                </div>
                <ul class="layui-menu friends_list" ref="friends_list_ref">
                    <li v-for="(item, index) in friends_list" :key="item.id"
                        :class="item.id == friend_id ? 'layui-menu-item-checked' : ''">
                        <div class="layui-row">
                            <div class="sel_friend" v-show="sel_friend">
                                <input type="checkbox" lay-ignore name="sel_friend" lay-skin="primary" :id="item.wxid"
                                    :value="item.wxid" style="width: 28px;height:28px;margin-top: 10px;"
                                    v-model="share_friends">
                            </div>
                            <div class="layui-col-xs12 layui-menu-body-title friend_right" v-on:click="chatWith(item)">
                                <div :class="item.id+'_'+item.type+'_'+item.dnd"></div>
                                <div class="layui-row">
                                    <div class="layui-col-xs4">
                                        <div class="headimg">
                                            <img :src="item.headimgurl"
                                                style="width:50px;height:50px;border-radius:10%">
                                            <span class="layui-badge-dot" v-if="item.new"></span>
                                        </div>
                                    </div>
                                    <div class="layui-col-xs6">
                                        <div class="name"><span>{{item.nickname}}</span></div>
                                        <div class="last_chat">
                                            <div class="layui-word-aux" v-html="item.last_chat_content"></div>
                                        </div>
                                    </div>
                                    <div class="layui-col-xs2">
                                        <i class="layui-icon layui-icon-mute" v-if="item.dnd"></i>
                                    </div>

                                </div>
                            </div>

                        </div>
                    </li>
                </ul>
                <div class="sel_friend" v-show="sel_friend">
                    <div>
                        <label>转发内容：</label><input type="input" autocomplete="off" class="layui-input" disabled
                            v-model="share_content[0].content">
                        <input type="input" autocomplete="off" class="layui-input" placeholder="给朋友留言"
                            v-model="leave_word">
                    </div>
                    <div class="btn_group" style="text-align: right;">
                        <button type="button" class="layui-btn layui-btn-sm layui-btn-primary layui-border-green"
                            lay-submit="" @click="forwardMsg">发送</button>
                        <button type="button" class="layui-btn layui-btn-sm layui-btn-primary layui-border-green"
                            lay-submit="" @click="cancelForward">取消</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- 聊天框 -->
        <div class="layui-col-xs5" class="chat_box">
            <div class="layui-panel chat_box_panel">
                <div class="layui-card-header" v-show="friend_info">{{friend_info.nickname}}</div>
                <div class="layui-panel chat_box_panel" v-show="show_chat">
                    <!-- <div><a href="javaScript:" @click="loadChatLogNext" v-show="show_more_chat_log">查看更多消息</a></div> -->
                    <div style="padding: 15px" class="chat_panel" id="chat_panel" ref="chat_log_list_ref">
                        <div class="scroll">
                            <div v-for="(item, index) in current_chat" :key="item.msg_id" :class="item.class">
                                <div class="layui-row" v-show="item.date">
                                    <div class="layui-col-md12" class="send_time" style="text-align:center">
                                        <span class="layui-badge layui-bg-gray">{{item.date}}</span>
                                    </div>
                                </div>
                                <!-- 我的发送 -->
                                <div class="layui-row" v-if="item.class == 'my_chat_content'">
                                    <div class="layui-col-md1" v-show="show_sel">
                                        <input type="checkbox" lay-ignore lay-skin="primary" title=""
                                            :id="'sel_chat'+'item.msg_id'"
                                            :value="{'msg_type':item.msg_type,'content':item.content,'type':'send','msg_id':item.msg_id}"
                                            v-model="sel_chat_content">
                                    </div>
                                    <div class="layui-col-md9 content">
                                        <blockquote class="layui-elem-quote">
                                            <!-- 文本消息 -->
                                            <div v-if="item.msg_type == 1" :class="'send_1_'+item.msg_id"
                                                v-html="item.content">
                                            </div>
                                            <!-- 图片消息 -->
                                            <div v-else-if="item.msg_type == 3" :class="'send_3_'+item.msg_id">
                                                <div class="layer-photos">
                                                    <img :src="item.content" style="width:100px;"
                                                        :layer-src="item.content">
                                                </div>
                                            </div>
                                            <!-- 文件消息 -->
                                            <div v-else-if="item.msg_type == 2004" :class="'send_2004_'+item.msg_id">
                                                <span v-if="item.content == ''|| !item.content">文件正在加载中</span>
                                                <a v-else :href="item.content.url" target="downloadFile">
                                                    <div class="layui-card">
                                                        <div class="layui-card-header">{{item.content.file_name}}</div>
                                                        <div class="layui-card-body">
                                                            <i
                                                                class="layui-icon layui-icon-file-b">{{item.content.ext}}</i>
                                                        </div>
                                                    </div>
                                                </a>
                                            </div>
                                            <!-- 名片消息 -->
                                            <div v-else-if="item.msg_type == 42" :class="'send_42_'+item.msg_id">
                                                <a href="javascript:" @click="openCard(item)">
                                                    <div class="layui-card">
                                                        <div class="layui-card-header">
                                                            <img :src="item.content.headimgurl" style="width:50px;">
                                                            <span>{{item.content.nickname}}</span>
                                                        </div>
                                                        <div class="layui-card-body">
                                                            <span>个人名片</span>
                                                        </div>
                                                    </div>
                                                </a>
                                            </div>
                                            <!-- 视频消息mp4 -->
                                            <div v-else-if="item.msg_type == 43" :class="'send_43_'+item.msg_id">
                                                <div v-if="item.content"><embed :src="item.content" autostart=false
                                                        width="300px" height="400px"></div>
                                                <div v-else>视频加载中<i
                                                        class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                                                </div>
                                            </div>
                                            <!-- 语音消息mp3 -->
                                            <div v-else-if="item.msg_type == 34" :class="'send_34_'+item.msg_id">
                                                <embed :src="item.content" autostart=false>
                                            </div>
                                            <!-- 分享链接 -->
                                            <div v-else-if="item.msg_type == 49" :class="'send_49_'+item.msg_id">
                                                <a :href="item.content.url" target="_blank">
                                                    <div class="layui-card">
                                                        <div class="layui-card-header">{{item.content.title}}</div>
                                                        <div class="layui-card-body">
                                                            {{item.content.des}}
                                                        </div>
                                                    </div>
                                                </a>
                                            </div>
                                        </blockquote>
                                    </div>
                                    <div class="layui-col-md1">
                                        <div class="headimg">
                                            <img :src="item.headimgurl"
                                                style="width:50px;height:50px;border-radius:10%">
                                        </div>
                                    </div>
                                </div>
                                <!-- 接收好友消息 -->
                                <div class="layui-row" v-else>
                                    <div class="layui-col-md1 sel_chat" v-show="show_sel">
                                        <input type="checkbox" lay-ignore lay-skin="primary" title=""
                                            :id="'sel_chat'+'item.msg_id'"
                                            :value="{msg_type:'item.msg_type',content:'item.content','type':'receive','msg_id':item.msg_id}"
                                            v-model="sel_chat_content">
                                    </div>
                                    <div class="layui-col-md1">
                                        <!-- 好友信息 -->
                                        <div v-if="item.friend_type == 'friend'">
                                            <div class="headimg">
                                                <img :src="item.headimgurl"
                                                    style="width:50px;height:50px;border-radius:10%">
                                            </div>
                                        </div>
                                        <!-- 群聊信息 -->
                                        <div v-if="item.friend_type == 'group'">
                                            <a href="javascript:" @click="openGroupCard(item)">
                                                <div class="headimg">
                                                    <img :src="item.group_headimg"
                                                        style="width:50px;height:50px;border-radius:10%">
                                                </div>
                                            </a>
                                            <span v-if="item.group_nickname != ''">{{item.group_nickname}}</span>
                                            <span v-else>{{item.group_from_name}}</span>
                                        </div>
                                    </div>
                                    <div class="layui-col-md9 content">
                                        <blockquote class="layui-elem-quote">
                                            <!-- 文本消息 -->
                                            <div v-if="item.msg_type == 1" :class="'receive_1_'+item.msg_id"
                                                v-html="item.content">
                                            </div>
                                            <!-- 引用消息 -->
                                            <div v-else-if="item.msg_type == 10003">
                                                <div :class="'receive_10003_'+item.msg_id" v-html="item.content.msg">
                                                </div>
                                                <div class="layui-form-mid layui-word-aux">
                                                    {{item.content.displayname}}：{{item.content.content}}
                                                </div>
                                            </div>
                                            <!-- 图片消息 -->
                                            <div v-else-if="item.msg_type == 3" :class="'receive_3_'+item.msg_id">
                                                <div class="layer-photos">
                                                    <img :src="item.content" style="width:100px;"
                                                        :layer-src="item.content">
                                                </div>
                                            </div>
                                            <!-- 文件消息 -->
                                            <div v-else-if="item.msg_type == 2004" :class="'receive_2004_'+item.msg_id">
                                                <span v-if="item.content == '' || !item.content">收到文件，正在加载中</span>
                                                <a v-else :href="item.content.url" target="downloadFile">
                                                    <div class="layui-card">
                                                        <div class="layui-card-header">{{item.content.file_name}}</div>
                                                        <div class="layui-card-body">
                                                            <i
                                                                class="layui-icon layui-icon-file-b">{{item.content.ext}}</i>
                                                        </div>
                                                    </div>
                                                </a>

                                            </div>
                                            <!-- 语音消息mp3 -->
                                            <div v-else-if="item.msg_type == 34" :class="'receive_34_'+item.msg_id">
                                                <embed :src="item.content" autostart=false>
                                            </div>
                                            <!-- 名片消息 -->
                                            <div v-else-if="item.msg_type == 42" :class="'receive_42_'+item.msg_id">
                                                <a href="javascript:" @click="openCard(item)">
                                                    <div class="layui-card">
                                                        <div class="layui-card-header">
                                                            <img :src="item.content.headimgurl" style="width:50px;">
                                                            <span>{{item.content.nickname}}</span>
                                                        </div>
                                                        <div class="layui-card-body">
                                                            <span>个人名片</span>
                                                        </div>
                                                    </div>
                                                </a>
                                            </div>
                                            <!-- 视频消息mp4 -->
                                            <div v-else-if="item.msg_type == 43" :class="'receive_43_'+item.msg_id">
                                                <span v-if="item.content == ''">收到视频，正在加载中</span>
                                                <embed v-else :src="item.content" autostart=false width="300px"
                                                    height="400px">
                                            </div>
                                            <!-- gif -->
                                            <div v-else-if="item.msg_type == 47" :class="'receive_47_'+item.msg_id">
                                                <div class="layer-photos">
                                                    <img :src="item.content" style="width:100px;"
                                                        :layer-src="item.content">
                                                </div>
                                            </div>
                                            <!-- 地理位置 -->
                                            <div v-else-if="item.msg_type == 48" :class="'receive_48_'+item.msg_id"
                                                v-html="item.content">
                                            </div>
                                            <!-- 分享链接 -->
                                            <div v-else-if="item.msg_type == 49" :class="'receive_49_'+item.msg_id">
                                                <a :href="item.content.url" target="_blank">
                                                    <div class="layui-card">
                                                        <div class="layui-card-header">{{item.content.title}}</div>
                                                        <div class="layui-card-body">
                                                            {{item.content.des}}
                                                        </div>
                                                    </div>
                                                </a>
                                            </div>
                                            <!-- 转账 -->
                                            <div v-else-if="item.msg_type == 2000" :class="'receive_2000_'+item.msg_id"
                                                @click="transfer(item)">
                                                <span>转账：</span>
                                                <i class="layui-icon layui-icon-rmb">{{item.content.money}}</i>
                                            </div>
                                            <!-- 红包 -->
                                            <div v-else-if="item.msg_type == 2001" :class="'receive_2001_'+item.msg_id"
                                                v-html="item.content">
                                            </div>
                                            <!-- 群邀请 -->
                                            <div v-else-if="item.msg_type == 2003" :class="'receive_2003_'+item.msg_id"
                                                v-html="item.content">
                                            </div>
                                            <!-- 其他 -->
                                            <div v-else :class="'receive_'+item.msg_type+'_'+item.msg_id"
                                                v-html="item.content">
                                            </div>
                                        </blockquote>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-show="show_multiple">
                        <div class="layui-panel">
                            <div class="layui-row">
                                <div class="layui-col-md1" style="float:right">
                                    <a href="javascrip::" @click="cancelForward"><i
                                            class="layui-icon layui-icon-close"></i></a>
                                </div>
                            </div>
                            <div class="layui-row">
                                <div class="layui-col-md2" style="text-align: center;">
                                    <div><button type="button" @click="batchForwardMsg"
                                            class="layui-btn layui-btn-primary layui-border-green layui-btn-radius  layui-btn-sm"><i
                                                class="layui-icon layui-icon-release"></i></button></div>
                                    <div style="color: #c2c2c2;font-size: 8px;"><span>逐条转发</span></div>
                                </div>
                                <div class="layui-col-md2" style="text-align: center;">
                                    <div><button type="button" @click="batchFavoritesMsg"
                                            class="layui-btn layui-btn-primary layui-border-green layui-btn-radius  layui-btn-sm"><i
                                                class="layui-icon layui-icon-star"></i></button></div>
                                    <div><span style="color: #c2c2c2;font-size: 8px;">收藏</span></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-show="!show_multiple">
                        <div class="send_file layui-form layui-border-box layui-table-view layui-table-view-1">
                            <div class="layui-table-tool">
                                <div class="layui-table-tool-temp"></div>
                                <div class="layui-table-tool-container">
                                    <div class="layui-inline" title="表情" lay-event="LAYTABLE_COLS" @click="openEmoji"><i
                                            class="layui-icon layui-icon-face-smile-b"></i></div>
                                    <div class="layui-inline" title="发送图片" lay-event="LAYTABLE_EXPORT"
                                        @click="choosePicture"><i class="layui-icon layui-icon-picture"></i></div>
                                    <div class="layui-inline" title="发送视频" lay-event="LAYTABLE_EXPORT"
                                        @click="chooseVideo"><i class="layui-icon layui-icon-play"></i></div>
                                    <div class="layui-inline" title="发送文件" lay-event="LAYTABLE_EXPORT"
                                        @click="chooseFile"><i class="layui-icon layui-icon-export"></i></div>
                                    <!-- <div class="layui-inline" title="发送文件" lay-event="LAYTABLE_PRINT" id="chooseFile">
                                        <i class="layui-icon layui-icon-export"></i></a>
                                    </div> -->
                                </div>
                            </div>
                            <textarea style="height: 181px;" placeholder="" class="layui-textarea" v-model="content"
                                id="content" @keyup.ctrl.enter="sendMsg"></textarea>
                        </div>
                        <div class="input_area" style="text-align:right">
                            <button type="button" class="layui-btn layui-btn-primary" @click="clearMsg">清空</button>
                            <button type="button" class="layui-btn" lay-submit="" @click="sendMsg" lay-filter="send"
                                id="id_send" @mouseover="sendTip()" @mouseout="closeTip()"><i
                                    class="layui-icon layui-icon-release"></i> 发送</button>
                            <button v-if="friend_info.type == 'group'" type="button" class="layui-btn" lay-submit=""
                                @click="openGroupMember">
                                <i class="layui-icon layui-icon-release"></i> 发送并@</button>
                        </div>
                    </div>
                </div>
                <!-- </div> -->

            </div>
        </div>
        <!-- 话术 -->
        <div class="layui-col-xs3 speechcraft" v-show='show_info'>
            <form class="layui-form layui-panel" lay-filter="speechcraft_filter">
                <div class="layui-row" style="padding: 15px;padding-bottom: 0;">
                    <div class="layui-col-md12 remark">
                        <div class="layui-card-header" style="text-align:center">客户备注
                            <button type="button" class="layui-btn layui-btn-xs pull-right"
                                @click="saveRemark">保存</button>
                        </div>
                        <div class="layui-card-body">
                            <textarea placeholder="客户备注" class="layui-textarea"
                                v-model="friend_info.remark_name"></textarea>
                        </div>
                    </div>
                </div>
                <hr>
                <div class="layui-row">
                    <div class="layui-col-md12" class="info">
                        <div class="layui-card">
                            <div class="layui-card-header" style="text-align:center">客户资料</div>
                            <div class="layui-card-body">
                                <div>
                                    <span class="info">{{friend_info.nickname}}</span><span
                                        class="info">{{friend_info.wxid}}</span>
                                </div>
                                <div>
                                    <span class="info">{{friend_info.sex == 1 ? '男':'女'}}</span>
                                    <span class="info">{{friend_info.province}}{{friend_info.city}}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-row">
                    <div class="layui-col-md12 reply">
                        <div class="layui-card">
                            <div class="layui-card-header" style="text-align:center">快捷回复
                                <button type="button"
                                    class="layui-btn layui-btn-radius layui-btn-primary layui-btn layui-btn-xs add_reply"
                                    @click="openAddSpeechcraft">
                                    <i class="layui-icon layui-icon-add-1"></i>
                                </button>
                            </div>
                            <div class="layui-card-body">
                                <div class="layui-collapse" style="height: 258px;overflow: scroll;"
                                    ref="speechcraft_list_ref">
                                    <div class="layui-colla-item" v-for="(item, index) in speechcraft_list"
                                        :key="item.id">
                                        <h2 class="layui-colla-title">{{item.title}}</h2>
                                        <div class="layui-colla-content copy_speechcraft"
                                            @click="copySpeechcraft(item.content)">
                                            <p>{{item.content}}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-row">
                    <div class="layui-col-md12" class="info">
                        <div class="layui-card">
                            <div class="layui-card-header" style="text-align:center">
                                <span>好友添加自动通过</span>
                                <input type="checkbox" lay-ignore name="open" lay-skin="switch" lay-filter="switchTest"
                                    v-model="auto_pass" lay-text="ON|OFF" @change="saveAutoPass">
                            </div>
                            <div class="layui-card-body" style="text-align:right">
                                <textarea placeholder="通过后默认回复话术" class="layui-textarea"
                                    v-model="auto_reply"></textarea>
                                <span class="pull-left">通过后自动回复</span>
                                <button class="layui-btn layui-btn-xs" lay-submit="" type="button"
                                    lay-filter="save_default_reply" @click="saveAutoReply">保存</button>
                            </div>

                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="__JS__/admin/vue@2.7.10.js" charset="utf-8"></script>
<script src="__LIB__/clipboard/clipboard.min.js" charset="utf-8"></script>
<script>
    // layui.use(['layer'], function () {
    //     var layer = layui.layer;

    //获取机器人参数
    var get_bot_param = {
        // 分页
        page: 1, // 当前页
        page_size: 10, // 每页总条数
        page_count: 1, // 总页数
    };
    //获取好友列表参数
    var get_friends_param = {
        // 分页
        page: 1, // 当前页
        page_size: 20, // 每页总条数
        page_count: 1, // 总页数
    }
    //获取话术参数
    var get_speechcraft_param = {
        // 分页
        page: 1, // 当前页
        page_size: 10, // 每页总条数
        page_count: 1, // 总页数
    }
    //获取聊天记录
    var get_chat_log_param = {
        // 分页
        page: 1, // 当前页
        page_size: 10, // 每页总条数
        page_count: 1, // 总页数
    }
    var data = {
        get_bot_param: get_bot_param,//获取机器人参数
        bot_list: [],//机器人列表
        get_friends_param: get_friends_param,//获取好友参数
        friends_list: [],//好友列表
        bot_id: 0,//当前机器人
        bot_info: {},
        friend_id: 0,//当前好友
        friend_info: {},//当前好友信息
        content: '',//当前发送的信息
        search_friend: '',
        // visibility:visible
        show_info: false,//好友信息
        show_sel: false,//聊天复选框
        get_speechcraft_param: get_speechcraft_param,//获取话术参数
        speechcraft_list: [],//话术列表
        chat_log: {},//聊天内容
        show_chat: false,
        quote: '',//引用
        auto_pass: false,
        auto_reply: '',
        new_msg_wxid: [],
        bot_uin: '',//机器人微信
        friend_wxid: '',//好友微信
        current_chat: [],
        new_bot: [],//新机器人消息
        new_friend: [],//新好友消息
        content_type: 1,//1/文本消息 3/图片消息
        sel_friend: false,
        // auto_pass_init: 0,//初始化auto_pass
        share_content: [{ msg_type: 1, content: '' }],//转发内容
        share_friends: [],//转发的好友
        // share_type: 1,//转发内容类型
        leave_word: '',
        show_multiple: false,
        sel_chat_content: [],//多选
        get_chat_log_param: get_chat_log_param,//获取聊天记录参数
        show_more_chat_log: true,
        tip: ''
    };
    var vm = new Vue({
        el: '#app',
        data: data,
        created() {
            this.getBotData();
            this.renderUpload();
            this.checkNewMsg();
        },
        mounted() {
            this.$refs.bot_list_ref.addEventListener('scroll', this.loadBot) // 滚动到底部，再加载的处理事件
            this.$refs.friends_list_ref.addEventListener('scroll', this.loadFriends) // 滚动到底部，再加载的处理事件
            this.$refs.speechcraft_list_ref.addEventListener('scroll', this.loadSpeechcraft) // 滚动到底部，再加载的处理事件
            this.$refs.chat_log_list_ref.addEventListener('scroll', this.loadChatLog) // 滚动到底部，再加载的处理事件
        },
        methods: {
            clearMsg() {
                this.content = '';
            },
            //搜索客服机器人
            getBotData: function () {
                let self = this;
                let url = "/admin/kefu/getBot";
                var index = layer.load(2);
                let page = this.get_bot_param.page;
                let limit = this.get_bot_param.page_size;
                let params = {
                    page: page,
                    limit: limit,
                }
                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        self['get_bot_param'].page_count = Math.ceil(res.data.total / limit);
                        self['bot_list'] = self['bot_list'].concat(res.data.list);
                        if (page == 1) {
                            if (self['bot_list'].length > 0) {
                                let cookie_bot_info = $.cookie('bot_info');
                                if (cookie_bot_info) {
                                    let bot_info = JSON.parse(cookie_bot_info);
                                    self['bot_info'] = bot_info;
                                    self['bot_id'] = bot_info.id;
                                    self['bot_uin'] = bot_info.uin;
                                    self['getFriendsData'](bot_info);

                                } else {
                                    self['bot_info'] = self['bot_list'][0];
                                    self['bot_id'] = self['bot_list'][0].id;
                                    self['bot_uin'] = self['bot_list'][0].uin;
                                    self['getFriendsData'](self['bot_info']);
                                }

                            } else {
                                self['addBot']();
                            }
                        }
                        //遍历创建客服聊天数据
                        $.each(self['bot_list'], function (i, v) {
                            let v_uin = v.uin;
                            self['chat_log'][[v_uin]] = {};
                            //消息点亮
                            if (self['new_bot'].includes(v_uin)) {
                                self['bot_list'][i].new = 1;
                                // let new_bot_arr = self['new_bot'];
                                // new_bot_arr.splice($.inArray(v_uin,new_bot_arr),1);
                                // self['new_bot'] = new_bot_arr;
                                // console.log(self['new_bot']);
                            }
                        });
                    }
                    layer.close(index);
                }, 'json');
            },
            // 滚动加载
            loadBot(e) {
                let scrollTop = e.target.scrollTop // 滚动条滚动时，距离顶部的距离
                let windowHeight = e.target.clientHeight // 可视区的高度
                let scrollHeight = e.target.scrollHeight // 滚动条的总高度
                // 滚动条到底部
                if (scrollTop + windowHeight === scrollHeight) {
                    this.get_bot_param.page++
                    if (this.get_bot_param.page > this.get_bot_param.page_count) return
                    this.getBotData()
                }
            },
            //点击机器人
            getFriendsData(item) {
                let self = this;
                let url = "/admin/kefu/getFriends";
                var index = layer.load(2);
                let page = this.get_friends_param.page;
                let limit = this.get_friends_param.page_size;
                //重新选择客服
                // console.log(self['bot_id']);console.log(item.id);
                if (self['bot_id'] != item.id) {
                    self['bot_id'] = item.id;
                    this.friends_list = [];
                    this.friend_info = {};
                    this.friend_id = 0;
                    this.bot_info = item;
                    this.bot_uin = item.uin;
                    this.get_friends_param.page = 1;
                    page = 1;
                    this.show_info = false;
                    this.show_chat = false;
                    this.get_speechcraft_param.page = 1;
                    this.speechcraft_list = [];
                    this.friend_wxid = '';
                    // this.auto_pass_init = 0;//需重新赋值
                }
                //如果有机器人有新信息，改为已读
                if (item.new) {
                    $.each(this.bot_list, function (i, v) {
                        if (item.uin == v.uin) {
                            // console.log(this.bot_list);
                            self['bot_list'][i].new = 0;
                            let new_bot_arr = self['new_bot'];
                            new_bot_arr.splice($.inArray(item.uin, new_bot_arr), 1);
                            self['new_bot'] = new_bot_arr;
                            return false;
                        }
                    })
                }
                let params = {
                    page: page,
                    limit: limit,
                    id: item.id,
                    search_key: this.search_friend
                }

                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        self['get_friends_param'].page_count = Math.ceil(res.data.total / limit);
                        self['friends_list'] = self['friends_list'].concat(res.data.list);
                        //消息点亮
                        $.each(self['friends_list'], function (i, v) {
                            if (self['new_friend'].includes(v.wxid)) {
                                self['friends_list'][i].new = 1;
                                // let new_friend_arr = self['new_friend'];
                                // new_friend_arr.splice($.inArray(v.wxid,new_friend_arr),1);
                                // self['new_friend'] = new_friend_arr;
                            }
                        })
                        self['renderFriendRight']();
                    }
                    layer.close(index);
                }, 'json');
                this.speechcraft_list = [];
                this.getSpeechcraftData();
                $.cookie('bot_info', JSON.stringify(this.bot_info));
            },
            //点击机器人
            clickFriend(item) {
                let self = this;
                let url = "/admin/kefu/getFriends";
                var index = layer.load(2);
                let page = this.get_friends_param.page;
                let limit = this.get_friends_param.page_size;
                //重新选择客服
                // console.log(self['bot_id']);console.log(item.id);
                if (self['bot_id'] != item.id || 1) {
                    self['bot_id'] = item.id;
                    this.friends_list = [];
                    this.friend_info = {};
                    this.friend_id = 0;
                    this.bot_info = item;
                    this.bot_uin = item.uin;
                    this.get_friends_param.page = 1;
                    page = 1;
                    this.show_info = false;
                    this.show_chat = false;
                    this.get_speechcraft_param.page = 1;
                    this.speechcraft_list = [];
                    this.friend_wxid = '';
                    // this.auto_pass_init = 0;//需重新赋值
                }
                //如果有机器人有新信息，改为已读
                if (item.new) {
                    $.each(this.bot_list, function (i, v) {
                        if (item.uin == v.uin) {
                            // console.log(this.bot_list);
                            self['bot_list'][i].new = 0;
                            let new_bot_arr = self['new_bot'];
                            new_bot_arr.splice($.inArray(item.uin, new_bot_arr), 1);
                            self['new_bot'] = new_bot_arr;
                            return false;
                        }
                    })
                }
                let params = {
                    page: page,
                    limit: limit,
                    id: item.id,
                    search_key: this.search_friend
                }

                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        self['get_friends_param'].page_count = Math.ceil(res.data.total / limit);
                        self['friends_list'] = self['friends_list'].concat(res.data.list);
                        console.log(self['new_friend']);
                        //消息点亮
                        $.each(self['friends_list'], function (i, v) {
                            if (self['new_friend'].includes(v.wxid)) {
                                self['friends_list'][i].new = 1;
                                // let new_friend_arr = self['new_friend'];
                                // new_friend_arr.splice($.inArray(v.wxid,new_friend_arr),1);
                                // self['new_friend'] = new_friend_arr;
                            }
                        })
                        self['renderFriendRight']();
                    }
                    layer.close(index);
                }, 'json');
                this.speechcraft_list = [];
                this.getSpeechcraftData();
                $.cookie('bot_info', JSON.stringify(this.bot_info));
            },
            // 滚动加载
            loadFriends(e) {
                // console.log('loadFriends');
                let id = this.bot_id;
                let bot_info = this.bot_info;
                let scrollTop = e.target.scrollTop // 滚动条滚动时，距离顶部的距离
                let windowHeight = e.target.clientHeight // 可视区的高度
                let scrollHeight = e.target.scrollHeight // 滚动条的总高度
                // 滚动条到底部
                if (scrollTop + windowHeight === scrollHeight) {
                    this.get_friends_param.page++
                    console.log('加载好友page：' + this.get_friends_param.page);
                    if (this.get_friends_param.page > this.get_friends_param.page_count) return
                    this.getFriendsData(bot_info)
                }
            },
            //获取当前选择的好友
            chatWith(item) {
                // console.log(item);
                let self = this;
                if (self['friend_id'] != item.id) {
                    self['friend_id'] = item.id;
                    this.friend_info = {};
                    this.friend_info = { id: item.id, nickname: item.nickname, remark_name: item.remark_name, wxid: item.wxid, sex: item.sex, province: item.province, city: item.city, type: item.type };
                    this.show_info = true;
                    this.show_chat = true;
                    this.friend_wxid = item.wxid;
                    this.show_more_chat_log = true;
                    this.get_chat_log_param.page = 1;
                    // console.log(this.friend_info);
                }
                // console.log(this.bot_info);
                //自动通过
                this.auto_pass = this.bot_info.auto_pass;
                this.auto_reply = this.bot_info.auto_reply;
                // this.auto_pass_init = 1;//初始化赋值完成
                //创建聊天数据
                if (!self['chat_log'][[this.bot_uin]][[this.friend_wxid]] || self['chat_log'][[this.bot_uin]][[this.friend_wxid]].length < 10) {
                    // self['chat_log'][[this.bot_uin]] = {[this.friend_wxid]:[]};
                    self['chat_log'][[this.bot_uin]][[this.friend_wxid]] = [];
                    this.getChatLog();
                }

                this.current_chat = self['chat_log'][[this.bot_uin]][[this.friend_wxid]];

                //如果新信息，改为已读
                if (item.new) {
                    $.each(this.friends_list, function (i, v) {
                        if (item.wxid == v.wxid) {
                            // console.log(this.bot_list);
                            self['friends_list'][i].new = 0;
                            let new_friend_arr = self['new_friend'];
                            new_friend_arr.splice($.inArray(v.wxid, new_friend_arr), 1);
                            self['new_friend'] = new_friend_arr;
                            return false;
                        }
                    });
                    //数据库更新已读
                    this.read(item.id);
                }

                this.renderElement();
                self['renderDropdown']();
                scroll();
                //判断是否全部已读
                let all_read = true;
                $.each(this.friends_list, function (i, v) {
                    if (v.new == 1) {
                        all_read = false;
                        return;
                    }
                })
                //全部已读，当前机器人红点取消
                if (all_read) {
                    // console.log('all_read');
                    $.each(this.bot_list, function (i, v) {
                        // console.log(self['bot_uin']);
                        // console.log(v);
                        if (self['bot_uin'] == v.uin) {
                            console.log('bot_read');
                            // console.log(this.bot_list);
                            self['bot_list'][i].new = 0;
                            let new_bot_arr = self['new_bot'];
                            new_bot_arr.splice($.inArray(item.uin, new_bot_arr), 1);
                            self['new_bot'] = new_bot_arr;
                            return false;
                        }
                    })
                }
                // this.current_chat.sort(function (a, b) {
                //     return b.last_chat_time - a.last_chat_time
                // });
            },
            //发送信息
            sendMsg(e) {
                let self = this;
                let content = this.content;
                var uin = this.bot_info.uin;
                var to_wxid = this.friend_info.wxid;
                if (!content) {
                    layer.msg('请输入内容');
                    return false;
                }
                let params = {
                    content: content,
                    uin: uin,
                    to_wxid: to_wxid,
                    bot_id: this.bot_id,
                    bot_info: this.bot_info,
                    quote: '引用内容引用内容',
                    friend_id: this.friend_id,
                    type: this.content_type
                }
                let url = "/admin/kefu/sendMsg";
                self['content'] = '';
                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        self['chat_log'][uin][[to_wxid]] = self['chat_log'][uin][[to_wxid]].concat(res.data);
                        self['current_chat'] = self['chat_log'][uin][[to_wxid]];
                        //是当前的机器人,好友列表排序,最后聊天记录
                        if (uin == res.data.friend.uin) {
                            $.each(self['friends_list'], function (i, v) {
                                if (v.wxid == res.data.friend.wxid) {
                                    self['friends_list'][i] = res.data.friend;
                                    return false;
                                }
                            });
                            self['friends_list'].sort(compare("last_chat_time", "desc"));

                        }
                        self['renderDropdown']();
                        scroll();
                        // self['searchFriend']();
                        self['sendToWx'](params);

                    }
                }, 'json');
            },
            //搜索好友
            searchFriend() {
                let self = this;
                let url = "/admin/kefu/getFriends";
                var index = layer.load(2);
                this.get_friends_param.page = 1;
                let page = this.get_friends_param.page;
                let limit = this.get_friends_param.page_size;
                this.friend_info = {};
                this.friend_id = 0;
                this.friend_wxid = '';
                let params = {
                    page: page,
                    limit: limit,
                    id: this.bot_id,
                    search_key: this.search_friend
                }

                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        self['get_friends_param'].page_count = Math.ceil(res.data.total / limit);
                        self['friends_list'] = [];
                        self['friends_list'] = self['friends_list'].concat(res.data.list);
                        self['show_info'] = false;
                        self['show_chat'] = false;
                        //消息点亮
                        $.each(self['friends_list'], function (i, v) {
                            if (self['new_friend'].includes(v.wxid)) {
                                self['friends_list'][i].new = 1;

                            }
                        })
                    }
                    layer.close(index);
                }, 'json');
            },
            //打开添加话术
            openAddSpeechcraft() {
                let self = this;
                let bot_id = this.bot_id;
                layer.open({
                    title: '快捷回复',
                    type: 2,
                    content: ['/admin/kefu/addSpeechcraft?bot_id=' + bot_id, 'no'],
                    area: ['650px', '320px'], //自定义文本域宽高
                    btn: ['保存', '取消'],
                    yes: function (index, layero) {
                        var body = layero.find("iframe").contents().find("body");
                        var params = $(body).find('form').serialize();
                        var url = '/admin/kefu/saveSpeechcraft';
                        $.post(url, params, function (res) {
                            if (res.code == 1) {
                                self['speechcraft_list'] = [];
                                self['getSpeechcraftData']();
                            }
                            layer.close(index);
                        }, 'json');
                    }
                });
            },
            //获取话术列表
            getSpeechcraftData() {
                let self = this;
                let url = "/admin/kefu/getSpeechcraft";
                var index = layer.load(2);
                let page = this.get_speechcraft_param.page;
                let limit = this.get_speechcraft_param.page_size;
                let params = {
                    page: page,
                    limit: limit,
                    bot_id: this.bot_id,
                }

                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        self['get_speechcraft_param'].page_count = Math.ceil(res.data.total / limit);
                        self['speechcraft_list'] = self['speechcraft_list'].concat(res.data.list);
                        self['renderElement']();
                    }
                    layer.close(index);
                }, 'json');
            },
            // 滚动加载话术列表
            loadSpeechcraft(e) {
                let scrollTop = e.target.scrollTop // 滚动条滚动时，距离顶部的距离
                let windowHeight = e.target.clientHeight // 可视区的高度
                let scrollHeight = e.target.scrollHeight // 滚动条的总高度
                // 滚动条到底部
                if (scrollTop + windowHeight === scrollHeight) {
                    this.get_speechcraft_param.page++
                    // console.log(this.get_speechcraft_param.page);console.log(this.get_speechcraft_param.page_count);
                    if (this.get_speechcraft_param.page > this.get_speechcraft_param.page_count) return
                    this.getSpeechcraftData()
                }
            },
            //更新渲染Element
            renderElement() {
                layui.use(['dropdown', 'util', 'layer', 'form'], function () {
                    var element = layui.element;
                    var layer = layui.layer;
                    var form = layui.form;
                    // console.log('更新渲染Element');
                    element.init();
                });
            },
            //更新渲染Form
            renderForm() {
                layui.use(['dropdown', 'util', 'layer', 'form'], function () {
                    var element = layui.element;
                    var layer = layui.layer;
                    var form = layui.form;
                    form.render();
                });
            },
            //保存备注名
            saveRemark() {
                let self = this;
                let remark_name = this.friend_info.remark_name.replace(/(^\s*)|(\s*$)/g, "");
                if (remark_name) {
                    let url = "/admin/kefu/saveRemark";
                    let params = {
                        remark_name: remark_name,
                        id: this.friend_id,
                        bot_id: this.bot_id,
                        to_wxid: this.friend_info.wxid,
                    }
                    var index = layer.load(2);
                    $.post(url, params, function (res) {
                        if (res.code == 1) {
                            self['friend_info'].remark_name = remark_name;
                        }
                        layer.close(index);
                    }, 'json');
                }
            },
            openEmoji(e) {
                layer.open({
                    type: 2,
                    content: '/admin/Emoji?type=vue',
                    area: ['600px', '500px'], //自定义文本域宽高
                });
            },
            //发送图片
            choosePicture(e) {
                layer.open({
                    type: 2,
                    title: '图片',
                    shadeClose: false,
                    shade: 0.8,
                    area: ['100%', '100%'],
                    content: ['{:url("media/choose", ["type" => "image", "field" => "content"])}', 'no'] //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                });
            },
            //发送图片
            chooseVideo(e) {
                layer.open({
                    type: 2,
                    title: '视频',
                    shadeClose: false,
                    shade: 0.8,
                    area: ['100%', '100%'],
                    content: ['{:url("media/choose", ["type" => "video", "field" => "content"])}', 'no'] //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                });
            },
            //发送文件
            chooseFile(e) {
                layer.open({
                    type: 2,
                    title: '文件',
                    shadeClose: false,
                    shade: 0.8,
                    area: ['100%', '100%'],
                    content: ['{:url("media/choose", ["type" => "file", "field" => "content"])}', 'no'] //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                });
            },
            //初始化layui上传
            renderUpload() {
                var self = this;
                layui.use(['upload', 'jquery', 'dropdown', 'util'], function () {
                    var upload = layui.upload
                        , $ = layui.jquery;
                    var upload_index;
                    var dropdown = layui.dropdown;
                    var util = layui.util;
                    upload.render({
                        elem: '#chooseFile'
                        , url: '{:url("uploader/filePost")}'
                        , multiple: false
                        , accept: 'file' //允许上传的文件类型
                        , size: "{(config('system.upload.file_size') ? config('system.upload.file_size')/1000 : 10240)}" //最大允许上传的文件大小
                        // , exts: "{(config('system.upload.file_ext') ? config('system.upload.file_ext') : 'jpg,gif,png,jpeg,zip,rar,tar,gz,7z,doc,docx,txt,xml,mp3,mp4,xls,xlsx,pdf,tar.gz')}".split(',').join('|')
                        , before: function () {
                            upload_index = layer.load(1);
                            // console.log(22);
                        }
                        , done: function (res, index, upload) { //上传后的回调
                            layer.close(upload_index);
                            if (res.code !== 1) {
                                layer.alert(res.msg);
                                return;
                            }
                            console.log(res.data);
                            let ext = res.data[0].ext;
                            let url = res.data[0].url;
                            let file_name = res.data[0].original_name;
                            let content = '';
                            if (ext == 'mp4') {
                                content = url;
                                self['content_type'] = 43;
                            } else {
                                content = { url: url, file_name: file_name, ext: ext };
                                self['content_type'] = 2004;
                            }
                            self['content'] = content;
                            self['sendMsg']();
                            self['content_type'] = 1;
                        }
                    });

                });
            },
            //右键
            renderDropdown(e) {
                var self = this;
                layui.use(['upload', 'jquery', 'dropdown', 'util', 'layer'], function () {
                    var upload = layui.upload
                        , $ = layui.jquery;
                    var upload_index;
                    var dropdown = layui.dropdown;
                    var util = layui.util;
                    var layer = layui.layer;
                    layer.photos({
                        photos: '.layer-photos'
                        , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                    });
                    //执行菜单
                    dropdown.render({
                        elem: '.layui-elem-quote' //在 id="demo" 的元素中触发事件。也可以直接设置为 document，从而重置整个右键菜单
                        , trigger: 'contextmenu' //右键事件
                        , data: [{
                            title: '复制'
                            , id: 1
                            , templet: '<div class="copy_msg">{{d.title}}</div>'
                        }, {
                            title: '转发'
                            , id: 2
                        }, {
                            title: '收藏'
                            , id: 3
                        }, {
                            title: '多选'
                            , id: 4
                        }], click: function (obj, othis) {
                            var dom = this.elem;
                            var content = $(dom).find('div').html();
                            var msg_type_class = $(dom).find('div').attr('class');
                            var msg_type_arr = msg_type_class.split("_");
                            var type = msg_type_arr[0];
                            var msg_type = msg_type_arr[1];
                            var msg_id = msg_type_arr[2];
                            // var class_name = $(dom).find('div').attr('class');
                            if (obj.id === 1) {
                                self['copySpeechcraft'](content, '.copy_msg');
                            } else if (obj.id === 2) {
                                self['sel_friend'] = true;
                                self['share_content'][0] = { msg_type: msg_type, content: content };
                                self['share_friends'] = [];
                                // self['share_type'] = msg_type;
                                console.log('转发');
                            } else if (obj.id === 3) {
                                if (type == 'send') {
                                    layer.msg("只能收藏接收的信息");
                                    return false;
                                }
                                let param = { content: content, msg_type: msg_type, msg_id: msg_id };
                                self['favoritesMsg'](param);
                                console.log('收藏');
                            } else if (obj.id === 4) {
                                self['show_multiple'] = true;
                                self['show_sel'] = true;

                                console.log('多选');
                            }
                        }
                    });
                });
            },
            //保存自动回复
            saveAutoReply(e) {
                let self = this;
                let url = "/admin/kefu/saveAutoReply";
                var auto_reply = this.auto_reply.trim();
                if (auto_reply == '') {
                    layer.msg('请输入自动回复内容');
                    return false;
                }
                let params = {
                    id: this.bot_id,
                    auto_reply: auto_reply,
                }
                //更新自动回复
                $.each(this.bot_list, function (i, v) {
                    if (v.id == params.id) {
                        v.auto_reply = params.auto_reply;
                        return false;
                    }
                });
                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        layer.msg('保存成功');
                    }
                }, 'json');
            },
            saveAutoPass() {
                let self = this;
                let url = "/admin/kefu/saveAutoReply";
                let params = {
                    id: this.bot_id,
                    auto_pass: this.auto_pass ? 1 : 0,
                }
                //更新自动回复
                $.each(this.bot_list, function (i, v) {
                    if (v.id == params.id) {
                        v.auto_pass = params.auto_pass;
                        return false;
                    }
                });
                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        layer.msg('保存成功');
                    }
                }, 'json');
            },
            //复制话术
            copySpeechcraft(content, class_name = '.copy_speechcraft') {
                // console.log(content);
                // console.log(class_name);
                // var clipboard = new ClipboardJS(class_name, {
                //     text: function (trigger) {
                //         return content;
                //     }
                // });
                // // console.log(clipboard);
                // clipboard.on('success', function (e) {
                //     layer.msg("已复制！");
                //     e.clearSelection();
                // });
                // clipboard.on('error', function (e) {
                //     console.error('Action:', e.action);
                //     console.error('Trigger:', e.trigger);
                // });
                //复制到对话框
                this.content = this.content + content;
            },
            //收藏信息
            favoritesMsg(params) {
                let self = this;
                let url = "/admin/kefu/favoritesMsg";
                params.robot_wxid = this.bot_info.uin;
                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        layer.msg('收藏成功');
                    }
                }, 'json');
            },
            //取消转发
            cancelForward() {
                this.leave_word = '';
                this.share_content = [{ msg_type: 1, content: '' }];
                this.share_friends = [];
                this.sel_friend = false;
                this.sel_chat_content = [];
                this.show_multiple = false;
                this.show_sel = false;
            },
            //转发消息
            forwardMsg() {
                let self = this;
                let share_friends = this.share_friends;
                let share_content = this.share_content;
                let share_type = this.share_type;
                let leave_word = this.leave_word.trim();;
                let uin = this.bot_info.uin;
                let bot_id = this.bot_id;
                let bot_info = this.bot_info;
                if (share_friends.length == 0) {
                    layer.msg('请选择转发的好友');
                    return false;
                }
                let emoji_url = '/admin/kefu/emojiConvert';
                //发送消息
                $.each(share_friends, function (i, v) {
                    //发送转发内容
                    $.each(share_content, function (i2, v2) {
                        //文本消息转emoji
                        if (v2.msg_type == 1) {
                            //emoji图片转换
                            $.post(emoji_url, { content: v2.content, to: 'emoji' }, function (res) {
                                let params = {
                                    content: res.data.content,
                                    uin: uin,
                                    to_wxid: v,
                                    bot_id: bot_id,
                                    bot_info: bot_info,
                                    quote: '',
                                    type: v2.msg_type,
                                }
                                self['sendMsgPost'](params);
                            }, 'json');
                        } else {
                            self['sendMsgPost'](params);
                        }


                    });

                    //发送留言
                    if (leave_word != '') {
                        let leave_params = {
                            content: leave_word,
                            uin: uin,
                            to_wxid: v,
                            bot_id: bot_id,
                            bot_info: bot_info,
                            quote: '',
                            type: 1
                        }
                        self['sendMsgPost'](leave_params);
                    }



                })

                this.cancelForward();
            },
            //发送信息
            sendMsgPost(params) {
                let self = this;
                // let content = this.content;
                let uin = params.uin;
                let to_wxid = params.to_wxid;
                // let params = {
                //     content: content,
                //     uin: uin,
                //     to_wxid: to_wxid,
                //     bot_id: this.bot_id,
                //     bot_info: this.bot_info,
                //     quote: '引用内容引用内容',
                //     friend_id: this.friend_id,
                //     type: this.content_type
                // }
                let url = "/admin/kefu/sendMsg";
                //创建聊天数据
                if (!self['chat_log'][[uin]][[to_wxid]]) {
                    // self['chat_log'][[this.bot_uin]] = {[this.friend_wxid]:[]};
                    self['chat_log'][[uin]][[to_wxid]] = [];
                }
                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        // console.log(uin);
                        // console.log(to_wxid);
                        // console.log(self['chat_log'][[uin]][[to_wxid]]);
                        self['chat_log'][[uin]][[to_wxid]] = self['chat_log'][[uin]][[to_wxid]].concat(res.data);
                        self['current_chat'] = self['chat_log'][[uin]][[to_wxid]];
                        //是当前的机器人,好友列表排序,最后聊天记录
                        if (uin == res.data.friend.uin) {
                            $.each(self['friends_list'], function (i, v) {
                                if (v.wxid == res.data.friend.wxid) {
                                    self['friends_list'][i] = res.data.friend;
                                    return false;
                                }
                            });
                            self['friends_list'].sort(compare("last_chat_time", "desc"));

                        }
                        self['renderDropdown']();
                        scroll();
                        self['sendToWx'](params);
                        // self['searchFriend']();
                    }
                }, 'json');
            },
            //批量转发消息
            batchForwardMsg() {
                let self = this;
                let share_content = this.sel_chat_content;
                if (share_content.length == 0) {
                    layer.msg('请选择转发内容');
                    return false;
                }
                self['sel_friend'] = true;
                self['share_content'] = share_content;
                self['share_friends'] = [];

            },
            //批量收藏
            batchFavoritesMsg() {
                let self = this;
                let share_content = this.sel_chat_content;
                if (share_content.length == 0) {
                    layer.msg('请选择转发内容');
                    return false;
                }
                let check = true;
                //发送的信息不能收藏
                $.each(share_content, function (i, v) {
                    if (v.type == 'send') {
                        check = false;
                        return false;
                    }

                });
                if (!check) {
                    layer.msg('不能收藏发送的信息,请检查');
                    return false;
                }
                $.each(share_content, function (i, v) {
                    if (v.type == 'receive') {
                        let param = { content: v.content, msg_type: v.msg_type, msg_id: v.msg_id };
                        self['favoritesMsg'](param);
                    }

                });

                this.cancelForward();

            },
            //获取当日聊天记录
            getChatLog() {
                let self = this;
                let url = "/admin/kefu/getChatLog";
                let uin = this.bot_info.uin;
                let friend_wxid = this.friend_info.wxid;
                let page = this.get_chat_log_param.page;
                let limit = this.get_chat_log_param.page_size;
                let params = {
                    uin: uin,
                    friend_wxid: friend_wxid,
                    page: page,
                    limit: limit,
                };
                // let load = layer.load();
                $.ajaxSettings.async = false;
                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        self['get_chat_log_param'].page_count = Math.ceil(res.data.total / limit);
                        // res.data.list.sort(compare("time"));
                        self['chat_log'][[uin]][[friend_wxid]] = self['chat_log'][[uin]][[friend_wxid]].concat(res.data.list);
                        // self['chat_log'][[uin]][[friend_wxid]] = self['chat_log'][[uin]][[friend_wxid]].unshift(res.data.list);
                        self['chat_log'][[uin]][[friend_wxid]].sort(compare("time"));
                    }
                    // layer.close(load);
                }, 'json');
            },
            // 滚动加载
            loadChatLog(e) {
                let scrollTop = e.target.scrollTop // 滚动条滚动时，距离顶部的距离
                // let windowHeight = e.target.clientHeight // 可视区的高度
                // let scrollHeight = e.target.scrollHeight // 滚动条的总高度
                // // 滚动条到底部
                // if (scrollTop + windowHeight === scrollHeight) {
                //     this.get_chat_log_param.page++
                //     if (this.get_chat_log_param.page > this.get_chat_log_param.page_count) return
                //     this.getChatLog()
                // }
                // console.log(scrollTop);
                if (scrollTop == 0) {
                    this.get_chat_log_param.page++
                    if (this.get_chat_log_param.page > this.get_chat_log_param.page_count) {
                        this.show_more_chat_log = false;
                        // layer.msg('没有更多消息');
                        return false;
                    }
                    this.getChatLog();
                    this.current_chat = this.chat_log[[this.bot_uin]][[this.friend_wxid]];
                    this.renderDropdown();
                    // console.log(document.querySelector('.scroll').scrollTop);
                    document.querySelector('.chat_panel').scrollTop = 1;
                    // vm.$nextTick(() => { document.querySelector('.scroll').scrollTop = 1000; })
                    // console.log('scrollTop2:'+document.querySelector('.chat_panel').scrollTop);
                }

            },
            //添加机器人
            addBot() {
                window.location.href = "/admin/kefu/loginBot";
                // layer.open({
                //     title: '添加机器人',
                //     type: 2,
                //     content: ['/admin/Kefu/loginBot'],
                //     area: ['500px', '700px'], //自定义文本域宽高
                // btn: ['保存', '取消'],
                // yes: function (index, layero) {
                //     var body = layero.find("iframe").contents().find("body");
                //     var params = $(body).find('form').serialize();
                //     var url = '/admin/kefu/saveSpeechcraft';
                //     $.post(url, params, function (res) {
                //         if (res.code == 1) {
                //             self['speechcraft_list'] = [];
                //             self['getSpeechcraftData']();
                //         }
                //         layer.close(index);
                //     }, 'json');
                // }
                // });
            },
            //发送微信消息
            sendToWx(params) {
                let url = '/admin/kefu/sendMsgPost';
                $.ajaxSettings.async = true;
                $.post(url, params, function (res) {

                }, 'json');
            },
            //同意/拒绝转账
            transfer(item) {
                let url = '/admin/kefu/checkTransferMsg';
                let params = item;
                let bot_id = this.bot_id;
                params.bot_id = bot_id;
                let from_wxid = this.friend_info.wxid;
                params.from_wxid = from_wxid;

                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        layer.open({
                            content: '是否同意转账？'
                            , btn: ['同意', '拒绝']
                            , yes: function (index, layero) {
                                let accepteTransferUrl = '/admin/kefu/accepteTransfer';
                                $.post(accepteTransferUrl, params, function (res) {
                                    if (res.code == 1) {
                                        layer.msg('已同意');
                                    }
                                }, 'json');
                            }
                            , btn2: function (index, layero) {
                                let rejectTransferUrl = '/admin/kefu/rejectTransfer';
                                $.post(rejectTransferUrl, params, function (res) {
                                    if (res.code == 1) {
                                        layer.msg('已拒绝');
                                    }
                                }, 'json');
                            }
                        });


                    } else {
                        layer.msg(res.msg);
                    }
                }, 'json');
            },
            openCard(item) {
                console.log('点击名片');
                console.log(item);
                //判断是否是好友
                let bot_uin = this.bot_info.uin;
                let check_url = '/admin/kefu/checkFirend';
                let check_params = { bot_uin: bot_uin, wxid: item.content.username };
                $.post(check_url, check_params, function (res) {
                    if (res.code == 1) {
                        let is_friend = res.data.is_friend;
                        let html = '<div class="layui-card">' +
                            '<div class= "layui-card-header" style="height:135px">' +
                            '<div style="margin:10px">' +
                            '<div><img src="' + item.content.headimgurl + '" style="width:50px;">' +
                            '<span style="margin-left:5px">' + item.content.nickname + '</span>';
                        if (item.content.sex == '男') {
                            html += '<span><i class="layui-icon layui-icon-male" style="color:#469ddb"></i>   </span></div>';
                        } else {
                            html += '<span><i class="layui-icon layui-icon-female" style="color:pink"></i>   </span></div>';
                        }

                        if (is_friend == 1) {
                            html += '<div><span>微信号:' + item.content.username + '</span></div>' +
                                '<div><span>地区:' + item.content.city + '</span></div>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layui-card-body" style="text-align: center;">';
                            let chat_item = res.data.friend;
                            // console.log(chat_item);
                            html += '<button type="button" lay-submit="" class="layui-btn" onclick="chatwith(' + JSON.stringify(chat_item).replace(/"/g, '&quot;') + ')">发消息</button>';
                        } else {
                            html += '<div><span>地区:' + item.content.city + '</span></div>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layui-card-body" style="text-align: center;">';
                            html += '<button type="button" lay-submit="" class="layui-btn" onclick="addFriend(' + JSON.stringify(item).replace(/"/g, '&quot;') + ')">添加到通讯录</button>';
                        }
                        html += '</div>' +
                            '</div >';
                        // console.log(html);
                        layer.open({
                            title: false,
                            type: 1,
                            content: html,

                        });

                    } else {
                        layer.msg(res.msg);
                    }
                }, 'json');
            },
            checkNewMsg() {
                self = this;
                setInterval(function () {
                    let bot_list = self['bot_list'];
                    $.each(bot_list, function (i, v) {
                        if (v.new == 1) {
                            speak_cn('有未处理的消息');
                            return false;
                        }
                    });
                }, 10000);
            },
            //换行
            lineFeed() {
                this.content = this.content + '\n';
            },
            sendTip() {
                // layer.msg('按Enter键发送，按ctrl+Enter键换行');

                this.tip = layer.tips('按ctrl+Enter键发送', '#id_send', { time: 0, tips: 1 });
            },
            closeTip() {
                layer.close(this.tip);
            },
            //显示群成员
            openGroupMember() {
                //获取群成员
                let self = this;
                let content = this.content;
                if (!content) {
                    layer.msg('请输入内容');
                    return false;
                }
                let group_id = this.friend_id;
                let uin = this.bot_uin;
                let url = '/admin/kefu/groupMember?uin=' + uin + '&group_id=' + group_id;
                layer.open({
                    type: 2,
                    title: '@群成员',
                    shadeClose: false,
                    shade: 0.8,
                    area: ['320px', '320px'],
                    content: [url] //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                });

            },
            //发送信息并@
            sendMsgAndAt(params) {
                let self = this;
                let group_id = this.friend_id;
                let uin = this.bot_uin;
                let bot_id = this.bot_id;
                let content = this.content;
                let to_wxid = this.friend_info.wxid;
                let friend_id = this.friend_id;
                let type = this.content_type;
                params.group_id = group_id;
                params.uin = uin;
                params.content = content;
                params.bot_id = bot_id;
                params.to_wxid = to_wxid;
                params.friend_id = friend_id;
                params.type = type;
                let url = "/admin/kefu/sendMsgAndAt";
                self['content'] = '';
                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        self['chat_log'][uin][[to_wxid]] = self['chat_log'][uin][[to_wxid]].concat(res.data);
                        self['current_chat'] = self['chat_log'][uin][[to_wxid]];
                        //是当前的机器人,好友列表排序,最后聊天记录
                        if (uin == res.data.friend.uin) {
                            $.each(self['friends_list'], function (i, v) {
                                if (v.wxid == res.data.friend.wxid) {
                                    self['friends_list'][i] = res.data.friend;
                                    return false;
                                }
                            });
                            self['friends_list'].sort(compare("last_chat_time", "desc"));

                        }
                        self['renderDropdown']();
                        scroll();
                        // self['searchFriend']();
                        self['sendToWxAndAt'](params);

                    }
                }, 'json');
            },
            sendToWxAndAt(params) {
                let url = '/admin/kefu/sendMsgAndAtPost';
                $.ajaxSettings.async = true;
                $.post(url, params, function (res) {

                }, 'json');
            },
            //发送信息并@所有人
            sendMsgAndAtAll() {
                let self = this;
                let group_id = this.friend_id;
                let uin = this.bot_uin;
                let bot_id = this.bot_id;
                let content = this.content;
                let to_wxid = this.friend_info.wxid;
                let friend_id = this.friend_id;
                let type = this.content_type;
                let params = {
                    content: content,
                    uin: uin,
                    to_wxid: to_wxid,
                    bot_id: this.bot_id,
                    bot_info: this.bot_info,
                    quote: '引用内容引用内容',
                    friend_id: this.friend_id,
                    type: this.content_type
                }

                let url = "/admin/kefu/sendMsgAndAtAll";
                self['content'] = '';
                $.post(url, params, function (res) {
                    if (res.code == 1) {
                        self['chat_log'][uin][[to_wxid]] = self['chat_log'][uin][[to_wxid]].concat(res.data);
                        self['current_chat'] = self['chat_log'][uin][[to_wxid]];
                        //是当前的机器人,好友列表排序,最后聊天记录
                        if (uin == res.data.friend.uin) {
                            $.each(self['friends_list'], function (i, v) {
                                if (v.wxid == res.data.friend.wxid) {
                                    self['friends_list'][i] = res.data.friend;
                                    return false;
                                }
                            });
                            self['friends_list'].sort(compare("last_chat_time", "desc"));

                        }
                        self['renderDropdown']();
                        scroll();
                        // self['searchFriend']();
                        self['sendToWxAndAtAll'](params);

                    }
                }, 'json');
            },
            sendToWxAndAtAll(params) {
                let url = '/admin/kefu/sendMsgAndAtAllPost';
                $.ajaxSettings.async = true;
                $.post(url, params, function (res) {

                }, 'json');
            },
            //群用户名片
            openGroupCard(item) {
                console.log('群用户名片');
                console.log(item);
                let self = this;
                let bot_id = this.bot_info.id;
                let group_wxid = item.from;
                let bot_uin = this.bot_info.uin;
                let info_url = '/admin/kefu/getGroupMemberInfo';
                let info_params = { bot_id: bot_id, group_wxid: group_wxid, member_wxid: item.group_from_wxid };
                $.post(info_url, info_params, function (res) {
                    if (res.code == 1) {
                        let info = res.data;
                        //判断是否是好友
                        let check_url = '/admin/kefu/checkFirend';
                        let check_params = { bot_uin: bot_uin, wxid: info.wxid };
                        $.post(check_url, check_params, function (res) {
                            if (res.code == 1) {
                                let is_friend = res.data.is_friend;
                                let html = '<div class="layui-card">' +
                                    '<div class= "layui-card-header" style="height:135px">' +
                                    '<div style="margin:10px">' +
                                    '<div><img src="' + info.headimgurl + '" style="width:50px;">' +
                                    '<span style="margin-left:5px">' + info.nickname + '</span>';
                                if (info.sex == 1) {
                                    html += '<span><i class="layui-icon layui-icon-male" style="color:#469ddb"></i>   </span></div>';
                                } else {
                                    html += '<span><i class="layui-icon layui-icon-female" style="color:pink"></i>   </span></div>';
                                }

                                if (is_friend == 1) {
                                    html += '<div><span>微信号:' + info.wx_num + '</span></div>' +
                                        '<div><span>地区:' + info.city + '</span></div>' +
                                        '</div>' +
                                        '</div>' +
                                        '<div class="layui-card-body" style="text-align: center;">';
                                    let chat_item = res.data.friend;
                                    // console.log(chat_item);
                                    html += '<button type="button" lay-submit="" class="layui-btn" onclick="chatwith(' + JSON.stringify(chat_item).replace(/"/g, '&quot;') + ')">发消息</button>';
                                } else {
                                    html += '<div><span>地区:' + info.city + '</span></div>' +
                                        '</div>' +
                                        '</div>' +
                                        '<div class="layui-card-body" style="text-align: center;">';
                                    html += '<button type="button" lay-submit="" class="layui-btn" onclick="addGroupFriend(' + JSON.stringify(item).replace(/"/g, '&quot;') + ')">添加到通讯录</button>';
                                }
                                html += '</div>' +
                                    '</div >';
                                // console.log(html);
                                layer.open({
                                    title: false,
                                    type: 1,
                                    content: html,

                                });

                            } else {
                                layer.msg(res.msg);
                            }
                        }, 'json');
                    } else {
                        layer.msg(res.msg);
                    }
                }, 'json');
            },
            //好友右键
            renderFriendRight(e) {
                console.log("好友右键");
                var self = this;
                layui.use(['upload', 'jquery', 'dropdown', 'util', 'layer'], function () {
                    var upload = layui.upload
                        , $ = layui.jquery;
                    var upload_index;
                    var dropdown = layui.dropdown;
                    var util = layui.util;
                    var layer = layui.layer;
                    layer.photos({
                        photos: '.layer-photos'
                        , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                    });
                    //执行菜单
                    var inst = dropdown.render({
                        elem: '.friend_right' //在 id="demo" 的元素中触发事件。也可以直接设置为 document，从而重置整个右键菜单
                        , trigger: 'contextmenu' //右键事件
                        , data: [{
                            title: '标记为未读'
                            , id: 1
                        }, {
                            title: '开启/关闭消息免打扰'
                            , id: 2
                        }], click: function (obj, othis) {
                            var dom = this.elem;
                            var content = $(dom).find('div').html();
                            var id_type_dnd = $(dom).find('div').attr('class');
                            var id_type_dnd_arr = id_type_dnd.split("_");
                            var friend_id = id_type_dnd_arr[0];
                            var friend_type = id_type_dnd_arr[1];
                            var dnd = id_type_dnd_arr[2];
                            // console.log(dnd);
                            //消息免打扰已打开
                            if (dnd == 1) {
                                // inst.reload({
                                //     data: [{
                                //         title: '标记为未读'
                                //         , id: 1
                                //     }, {
                                //         title: '开启新消息提醒'
                                //         , id: 2
                                //     }], // 新的数据
                                //     show: false, // 重载即显示
                                //     style: 'animation: none;' // 去除面板动画，防止高频重载时的抖动
                                // });
                                var dnd_flag = 0;
                            } else {
                                var dnd_flag = 1;
                            }
                            // console.log(dnd_flag);
                            if (obj.id === 1) {
                                console.log('标记为未读');
                                $.each(self['friends_list'], function (i, v) {
                                    if (friend_id == v.id) {
                                        v.new = 1;
                                        return false;
                                    }
                                });
                                // console.log(self['friends_list']);
                            } else if (obj.id === 2) {
                                $.each(self['friends_list'], function (i, v) {
                                    if (friend_id == v.id) {
                                        v.dnd = dnd_flag;
                                        return false;
                                    }
                                });
                                let url = '/admin/kefu/updateMemberDnd';
                                let params = { id: friend_id, dnd: dnd_flag, bot_id: self['bot_id'] };
                                $.post(url, params, function (res) {

                                }, 'json');
                            }
                        }
                    });
                });
            },
            //消息已读
            read(id) {
                let url = '/admin/kefu/updateMemberNew';
                let params = {id: id};
                $.post(url, params, function (res) {

                }, 'json');
            },

        }
    });
    // console.log(vm);

    var from_id = "{$from_id}";
    // var webSocket = new WebSocket("ws://127.0.0.1:9506");
    var webSocket = new WebSocket("ws://{$socket_ip}:{$socket_port}");
    webSocket.onerror = function (event) {
        console.log("onerror 错误： " + event.data);
    };
    // setInterval(function () {
    //         console.log(Date());
    //     }, 30000);
    // 打开websocket
    webSocket.onopen = function (event) {
        console.log('连接成功');
        //绑定用户
        var bild = '{"type":"bind","uid":"' + from_id + '"}';
        webSocket.send(bild);
        setInterval(function () {
            // console.log(Date());
            webSocket.send('heartbeat');    //发送内容不限，只是为了证明客户端还没关闭还在线
        }, 10000);

    };
    //监听消息
    webSocket.onmessage = function (event) {
        if (event.data) {
            console.log('收到客户端消息:' + event.data);
            var massage = eval("(" + event.data + ")");
            //收到私聊信息
            if (massage.event == 'msg') {

                //数据类型转换
                if (massage.msg_type == 2000 || massage.msg_type == 49 || massage.msg_type == 42 || massage.msg_type == 2004 || massage.msg_type == 10003) {
                    // console.log("转账：");
                    // console.log(massage.msg);
                    if (massage.msg != '') {
                        massage.msg = JSON.parse(massage.msg);
                    }
                    console.log("JSON.parse");
                    console.log(massage.msg);
                }
                //转账/分享链接单独处理
                let msg = { content: massage.msg, class: 'friends_chat_content', date: massage.date, headimgurl: massage.headimgurl, msg_id: massage.msg_id, msg_type: massage.msg_type, friend_type: massage.friend_type, group_headimg: massage.group_headimg, group_nickname: massage.group_nickname, friend: massage.friend };
                console.log(msg);
                if (massage.friend.dnd == 0) {
                    speak_cn('收到新消息');
                    var dnd = 0;
                } else {
                    var dnd = 1;
                    console.log('免打扰');
                }
                if (!vm['chat_log'][[massage.robot_wxid]]) {
                    vm['chat_log'][[massage.robot_wxid]] = {};
                }

                if (!vm['chat_log'][[massage.robot_wxid]][[massage.from_wxid]]) {
                    vm['chat_log'][[massage.robot_wxid]][[massage.from_wxid]] = [];
                }
                // console.log(vm['chat_log']);
                //已存在且不为空则不添加
                let add_flag = true;
                $.each(vm['chat_log'][[massage.robot_wxid]][[massage.from_wxid]], function (i, v) {
                    if (v.msg_id == massage.msg_id && v.content != '') {
                        add_flag = false;
                        return false;
                    }
                });
                if (add_flag) {
                    vm['chat_log'][[massage.robot_wxid]][[massage.from_wxid]] = vm['chat_log'][[massage.robot_wxid]][[massage.from_wxid]].concat([msg]);
                    if (massage.from_wxid == vm['friend_wxid']) {
                        vm['current_chat'] = vm['chat_log'][[massage.robot_wxid]][[massage.from_wxid]];
                    }
                }


                if (!vm['new_bot'].includes(massage.robot_wxid) && dnd == 0) {
                    vm['new_bot'].push(massage.robot_wxid);
                }
                vm['renderDropdown']();
                //机器人未读点亮
                //如果消息不是当前机器人则点亮
                var new_to_friend = true;
                $.each(vm['bot_list'], function (i, v) {
                    if (massage.robot_wxid == v.uin && dnd == 0) {
                        vm['bot_list'][i]['new'] = 1;
                        // let new_bot_arr = vm['new_bot'];
                        // new_bot_arr.splice($.inArray(v.uin,new_bot_arr),1);
                        // vm['new_bot'] = new_bot_arr;
                        // console.log(new_bot_arr);
                        return false;
                    }
                });
                console.log(vm['bot_list']);
                if (massage.robot_wxid != vm['bot_uin']) {
                    // $.each(vm['bot_list'], function (i, v) {
                    //     if (massage.robot_wxid == v.uin) {
                    //         vm['bot_list'][i]['new'] = 1;
                    //         // let new_bot_arr = vm['new_bot'];
                    //         // new_bot_arr.splice($.inArray(v.uin,new_bot_arr),1);
                    //         // vm['new_bot'] = new_bot_arr;
                    //         // console.log(new_bot_arr);
                    //         return false;
                    //     }
                    // })
                    // console.log(vm['bot_list']);
                } else {
                    //是当前机器人
                    //判断是否在好友列表里
                    //是替换
                    //否放入
                    //排序
                    console.log('是当前机器人')
                    var is_in = false;
                    $.each(vm['friends_list'], function (i, v) {
                        if (massage.from_wxid == v.wxid) {
                            vm['friends_list'][i] = massage.friend;
                            is_in = true;
                            return false;
                        }
                    })
                    if (!is_in) {
                        //不在当前好友列表里
                        massage.friend.new = 1;
                        vm['friends_list'] = vm['friends_list'].concat([massage.friend]);
                        // new_to_friend = false;
                        // console.log(vm['friends_list']);
                    } else {
                        //在当前好友列表
                        //是否当前选择的好友
                        //不是则点亮
                        if (massage.from_wxid != vm['friend_wxid']) {
                            $.each(vm['friends_list'], function (i, v) {
                                if (massage.from_wxid == v.wxid) {
                                    v.new = 1;
                                    v.last_chat_time = massage.friend.last_chat_time;
                                    return false;
                                }
                            })
                        }


                    }
                    // console.log('排序前好友列表');
                    // console.log(vm['friends_list']);
                    vm['friends_list'].sort(compare("last_chat_time", "desc"));
                    // console.log('排序后好友列表');
                    // console.log(vm['friends_list']);
                    //是当前好友滚动到底
                    if (massage.from_wxid == vm['friend_wxid']) {
                        scroll();
                    }

                }
                //点亮对应好友
                if (new_to_friend) {
                    console.log('点亮对应好友');
                    if (!vm['new_friend'].includes(massage.from_wxid)) {
                        vm['new_friend'].push(massage.from_wxid);
                    }
                    console.log(vm['new_friend']);
                }
                webSocket.send('client_get_msg');
            } else if (massage.event == 'new_friend') {
                //好友添加事件
                vm.searchFriend();
            } else if (massage.event == 'callback') {
                let msg = {
                    content: massage.content,
                    class: 'my_chat_content',
                    date: massage.date,
                    headimgurl: massage.headimgurl,
                    msg_id: massage.msg_id,
                    msg_type: massage.msg_type,
                    type: massage.type,
                };
                console.log('同步发送信息');
                // //判断是否为当前聊天
                if (massage.to == vm['friend_wxid']) {
                    if (!vm['chat_log'][[massage.robot_wxid]]) {
                        vm['chat_log'][[massage.robot_wxid]] = {};
                    }
                    if (!vm['chat_log'][[massage.robot_wxid]][[massage.to]]) {
                        vm['chat_log'][[massage.robot_wxid]][[massage.to]] = [];
                    }
                    let is_mobile_send = true;
                    //替换最后一条为send的msg_id
                    $.each(vm['chat_log'][[massage.robot_wxid]][[massage.to]], function (i, v) {
                        let first_msg_id = v.msg_id.substr(0, 1);
                        if (v.type == 'send' && first_msg_id == 's') {
                            v.msg_id = massage.msg_id;
                            is_mobile_send = false;
                        }
                    });
                    if (is_mobile_send) {
                        console.log("是手机端发送");
                        vm['chat_log'][[massage.robot_wxid]][[massage.to]] = vm['chat_log'][[massage.robot_wxid]][[massage.to]].concat([msg]);
                        vm['current_chat'] = vm['chat_log'][[massage.robot_wxid]][[massage.to]];
                        scroll();
                    }

                    $.each(vm['friends_list'], function (i, v) {
                        if (massage.to == v.wxid) {
                            v.last_chat_time = massage.friend.last_chat_time;
                            v.last_chat_content = massage.friend.last_chat_content;
                            return false;
                        }
                    })
                    vm['friends_list'].sort(compare("last_chat_time", "desc"));
                    vm['renderDropdown']();
                    return false;

                }
            } else if (massage.event == 'delay') {
                //数据类型转换
                if (massage.msg_type == 2000 || massage.msg_type == 49 || massage.msg_type == 42 || massage.msg_type == 2004) {
                    // console.log("转账：");
                    // console.log(massage.msg);
                    if (massage.msg != '') {
                        massage.msg = JSON.parse(massage.msg);
                    }
                    // console.log("1234");
                    console.log(massage.msg);
                }
                //延迟数据替换
                let replace = false;
                //是否替换成功
                $.each(vm['chat_log'][[massage.robot_wxid]][[massage.from_wxid]], function (i, v) {
                    if (v.msg_id == massage.msg_id) {
                        v.content = massage.msg;
                        replace = true;
                        return false;
                    }
                });
                //未替换成功，视频比提示先执行，直接加入
                if (!replace) {
                    console.log(vm['chat_log'][[massage.robot_wxid]][[massage.from_wxid]]);
                    let msg = { content: massage.msg, class: 'friends_chat_content', date: massage.date, headimgurl: massage.headimgurl, msg_id: massage.msg_id, msg_type: massage.msg_type, friend_type: massage.friend_type, group_headimg: massage.group_headimg, group_nickname: massage.group_nickname, friend: massage.friend };
                    vm['chat_log'][[massage.robot_wxid]][[massage.from_wxid]] = vm['chat_log'][[massage.robot_wxid]][[massage.from_wxid]].concat([msg]);
                }
                vm['current_chat'] = vm['chat_log'][[massage.robot_wxid]][[massage.from_wxid]];
                vm['renderDropdown']();
            }

        }
    };
    webSocket.onclose = function (event) {
        console.log("关闭: " + sockState());
        webSocket.close();
        layer.confirm('待机时间过长已断开连接，点击确定重新连接?', function (index) {
            location.reload();
            layer.close(index);
        });
    }
    function sockState() {
        var status = ['未连接', '连接成功，可通讯', '正在关闭', '连接已关闭或无法打开'];
        return status[webSocket.readyState];
    }


    //根据iframe传回的值进行当前页面的赋值
    function setPictureValue(value, field) {
        $.each(value, function (i, v) {
            let picture_url = v.url;
            vm.content = picture_url;
            vm.content_type = 3;
            vm.sendMsg();
            vm.content_type = 1;
        });


    }

    //根据iframe传回的值进行当前页面的赋值
    function setVideoValue(value, field) {
        $.each(value, function (i, v) {
            let max = 5000;
            let min = 1000;
            let time = Math.floor(Math.random() * (max - min + 1)) + min
            setTimeout(function () {
                let url = v.url;
                vm.content = url;
                vm.content_type = 43;
                vm.sendMsg();
                vm.content_type = 1;
            }, 1000);
        });
    }
    //根据iframe传回的值进行当前页面的赋值
    function setFileValue(value, field) {
        $.each(value, function (i, v) {
            let url = v.url;
            let content = { url: url, file_name: v.title, ext: v.ext };
            vm.content = content;
            vm.content_type = 2004;
            vm.sendMsg();
            vm.content_type = 1;
        });
    }
    function setAtValue(value) {
        var at_wxid = [];
        var at_wxid_str = '';
        var at_nickname = '';
        $.each(value, function (i, v) {
            at_wxid.push(v.wxid);
            at_nickname += '@' + v.group_nickname;
        });
        at_wxid_str = at_wxid.join(',');
        let params = { member_wxid: at_wxid_str, at_nickname: at_nickname };
        vm.sendMsgAndAt(params);
    }
    function atAll() {
        vm.sendMsgAndAtAll();
    }
    function compare(property, sort = 'asc') {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            if (sort == 'asc') {
                return value1 - value2;
            } else {
                return value2 - value1;
            }

        }
    }

    function scroll() {
        //    let res = document.querySelector('.scroll').clickHeight();
        //    console.log('scroll:'+res);
        // setTimeout(function(){
        //     console.log(document.querySelector('.scroll').clientHeight)
        // },2000)

        vm.$nextTick(() => { document.querySelector('.scroll').scrollIntoView(false); })

    }

    function chatwith(item) {
        layer.closeAll();
        //判断是否在当前好友列表
        $in = false;
        let time = new Date().getTime() + '';
        item.last_chat_time = time.substr(0, 10);
        $.each(vm['friends_list'], function (i, v) {
            if (item.wxid == v.wxid) {
                $in = true;
                v.last_chat_time = item.last_chat_time;
                return false;
            }
        })
        //不在好友列表
        //更新这个号的聊天时间，置顶聊天
        if (!$in) {
            let url = '/admin/kefu/updateChatTime';
            let param = { uin: vm['bot_uin'], wxid: item.wxid };
            $.post(url, param, function (res) {

            }, 'json');
            vm['friends_list'] = vm['friends_list'].concat([item]);
        }
        vm['friends_list'].sort(compare("last_chat_time", "desc"));

        vm['chatWith'](item);
    }

    //添加好友
    function addFriend(item) {
        console.log('添加好友');
        console.log(item);
        layer.closeAll();
        let url = '/admin/kefu/addFriend';
        let param = { uin: vm['bot_uin'], wxid: item.content.username, bot_id: vm['bot_id'], msg: item.content.nickname };
        $.post(url, param, function (res) {
            if (res.code == 1) {
                layer.msg('已发送请求!');
            } else {
                layer.alert(res.msg);
            }
        }, 'json');
    }

    //添加群好友
    function addGroupFriend(item) {
        console.log('添加群好友');
        console.log(item);
        layer.closeAll();
        let url = '/admin/kefu/addFriend';
        let param = { uin: vm['bot_uin'], wxid: item.wxid, bot_id: vm['bot_id'], msg: item.nickname };
        $.post(url, param, function (res) {
            if (res.code == 1) {
                layer.msg('已发送请求!');
            } else {
                layer.alert(res.msg);
            }
        }, 'json');
    }

    //语音播报
    function speak_cn(ttsText) {
        //var mess = document.getElementById('ttsText').value;
        var msg = new SpeechSynthesisUtterance(ttsText);
        msg.volume = 100;
        msg.rate = 1;
        msg.pitch = 1.5;
        console.log(msg);
        window.speechSynthesis.speak(msg);
    }
    // });
</script>
<style>
    .chat_box_panel {
        height: 776px;
    }

    .content {
        margin: auto 10px;
    }

    .my_chat_content blockquote {
        border-right: 5px solid #5fb878;
        border-left: 0px;
    }

    .chat_panel {
        height: 450px;
        overflow: scroll;
    }

    .info {
        margin-left: 20px;
    }

    .add_reply {
        margin-left: 5px;
    }

    .layui-form-switch {
        margin-top: 0;
    }

    .layui-textarea {
        resize: none;
    }

    .layui-colla-content {
        height: 100px;
        overflow: scroll;
    }

    .bot-panel {
        height: 820px;
        overflow: scroll;
    }

    .friends-panel {
        height: 820px;
        overflow: scroll;
    }

    .bot_list {
        margin-bottom: 30px;
    }

    .friends_list {
        height: 600px;
        overflow: scroll;
    }

    .gray_headimgurl {
        filter: grayscale(100%);
    }

    .headimg {
        padding-right: 5px;
    }

    .chat_panel .layui-elem-quote {
        word-wrap: break-word;
    }

    .chat_box_panel .layui-table-tool .layui-inline[lay-event] {
        border: none;
    }
</style>